﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using FlickrNet;
using FlickrDownloadr.Services;

namespace Flickr2Mesh
{
    public partial class FlickrAuthForm : Form
    {
        private string _frob;
        private bool _authorized = false;

        public FlickrAuthForm()
        {
            InitializeComponent();
        }

        private void FlickrAuthForm_Load(object sender, EventArgs e)
        {
            
        }

        private void Authorize()
        {
            Auth auth = PhotoService.Instance.Service.AuthGetToken(_frob);

            
            //Auth auth = FlickrService.Flickr.AuthGetToken(_frob);
            //FlickrService.Flickr.AuthToken = auth.Token;

            //Console.WriteLine("User authenticated successfully");
            //Console.WriteLine("Authentication token is " + auth.Token);
            //Console.WriteLine("User id is " + auth.User.UserId);
            
            PhotoService.Instance.PersistToken(auth.Token);
        }

        private void buttonAuthorize_Click(object sender, EventArgs e)
        {
            if (!_authorized)
            {
                LaunchWebsite();
            }
            else
            {
                try
                {
                    Authorize();

                    AuthorizeCompleted();
                }
                catch (FlickrException)
                {
                    var result = MessageBox.Show("Failed to authenticate you with Flickr. Please try to run the authorize process again and make sure you authorize Flickr2Mesh on the Flickr.com website.\r\n\r\nDo you want to try again?", "Failed to authenticate", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error);

                    if (result == DialogResult.Retry)
                    {
                        try
                        {
                            LaunchWebsite();

                            MessageBox.Show("Click the 'OK, I'll allow it' button on the Flickr.com website to authorize Flickr2Mesh to Read your photos.", "Please authorize", MessageBoxButtons.OK, MessageBoxIcon.Information);

                            Authorize();
                            AuthorizeCompleted();
                        }
                        catch (FlickrException)
                        {
                            MessageBox.Show("Failed to retry authentication. Please try again later.", "Failed to retry authentication", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            this.Close();
                        }
                    }
                    else
                    {
                        this.Close();
                    }
                }
            }
        }

        private void AuthorizeCompleted()
        {
            MessageBox.Show("Authorization Success. Thank You.", "Thank You.", MessageBoxButtons.OK, MessageBoxIcon.Information);
            this.Close();
        }

        private void LaunchWebsite()
        {
            //PhotoService.Instance.ResetToken();
            PhotoService.Instance.ResetAuthentication();
            
            try
            {
                _frob = PhotoService.Instance.Service.AuthGetFrob();
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("100"))
                    MessageBox.Show("Invalid API Key. Please make sure you have configured the application with correct keys.", "Invalid API Key", MessageBoxButtons.OK, MessageBoxIcon.Error);
                else
                    MessageBox.Show("Unknown error occurred. Exception: " + ex.Message, "Unknown error occurred", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return;
            }

            string flickrUrl = PhotoService.Instance.Service.AuthCalcUrl(_frob, FlickrNet.AuthLevel.Read);
            System.Diagnostics.Process.Start(flickrUrl);

            labelTitle.Text = "Return to this window after authorization process";
            labelDescription.Text = "Once you're done, click the 'Complete' button below and you can continue using Flickr Downloadr.";
            buttonAuthorize.Text = "Complete";

            _authorized = true;
        }
    }
}
